<template>
    <div class="login-page">
        <el-card class="login-card" shadow="hover">
            <div class="logo"></div>
            <h2 class="title">TMS智慧物流<br /></h2>

            <el-form :model="form" ref="loginForm" :rules="rules" class="login-form">
                <el-form-item prop="userName">
                    <el-input v-model="form.userName" placeholder="请输入用户名"></el-input>
                </el-form-item>

                <el-form-item prop="password">
                    <el-input v-model="form.password" placeholder="请输入登录密码" show-password type="password"></el-input>
                </el-form-item>

                <el-button type="primary" class="login-button" @click="onSubmit" round>登录</el-button>
            </el-form>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import http from '@/utils/http'
import axios from 'axios'

import { read } from '@/assets/Axios/axiosH'
import { useCounterStore } from '@/stores/counter'
const counts = useCounterStore();
const router = useRouter()

const loginForm = ref()

const form = reactive({
    userName: '',
    password: ''
})

// 表单校验规则：用户名和密码非空
const rules = {
    userName: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
    ]
}



async function onSubmit() {
    // 先校验表单（Element Plus），如果校验失败则阻止提交
    try {
        await new Promise<void>((resolve, reject) => {
            ; (loginForm.value as any)?.validate((valid: boolean) => {
                if (valid) resolve()
                else reject(new Error('validation failed'))
            })
        })
    } catch (_e) {
        ElMessage.warning('请填写用户名和密码')
        return
    }

    try {
        // 发送登录请求
        const response = await read({
            url: "/api/Login/Login",
            method: "post",
            params: {
                UserName: form.userName,
                Password: form.password
            }
        })
        if (response.data.code == 200) {
            ElMessage.success(response.data.mesg)
            const d = response.data.data || {}
            counts.Logins.UserId = d.userid ?? ''
            counts.Logins.Nickname = d.nickname ?? ''
            counts.Logins.Account = d.account ?? ''
            counts.Logins.Email = d.email ?? ''
            // 后端返回 role 数组，取第一个角色作为当前角色显示
            const firstRole = Array.isArray(d.role) && d.role.length > 0 ? d.role[0] : null
            counts.Logins.RoleId = firstRole?.roleid ?? ''
            counts.Logins.RoleName = firstRole?.roleName ?? ''
            // 保存角色列表到 pinia
            counts.setRoles(d.role || [])
            counts.Logins.token = d.token ?? ''

            // 登录判定
            // 登录成功，写JWT的 token到本地
            window.localStorage.setItem("token", response.data.data.token);
            // 数据提交后端要加入新的Token值
            axios.defaults.headers.common["Authorization"] =
                "Bearer " + response.data.data.token;


            // 登录成功后跳转到首页
            router.push('/Main')
        }


    } catch (err) {
        console.error('登录失败:', err)
        ElMessage.error((err as Error).message || '登录失败')
    }
}
</script>

<style scoped>
.login-page {
    width: 100%;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f7f7f7;
}

.login-card {
    width: 420px;
    background: #fff;
    padding: 40px 60px;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
    text-align: center;
}

.logo {
    width: 80px;
    height: 80px;
    margin: 0 auto 16px;
    border-radius: 50%;
    background: #7fc3a7;
}

.title {
    color: #66b88f;
    margin-bottom: 28px;
}

.login-form {
    text-align: left;
    margin-top: 8px;
}

.login-button {
    width: 100%;
    margin-top: 8px;
}
</style>
